package com.xmyr.cachedemo.sevice.impl;

import com.xmyr.cachedemo.pojo.DemoModel;
import com.xmyr.cachedemo.sevice.IDemoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author CCQ(QQ or weChat : 1330845068 ( 寻梦依然))
 * @version 1.0
 * @date 2022/3/27 11:57
 */
@Service
@Slf4j
@CacheConfig(cacheNames = "Demo")
public class DemoServiceImpl implements IDemoService {

    private static Map<Long, DemoModel> dataMap = new HashMap<>();
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
//    @Cacheable(value = "Demo",key = "#id")
    @Cacheable(key = "#id") // 存入redis为 DemoModel::id
    public DemoModel getById(Long id) {
        log.info("开始根据ID为{}查询Redis获取数据", id);
        DemoModel redisDemoModel = (DemoModel) redisTemplate.opsForValue().get("Demo::" + id);
        if(redisDemoModel != null){
            return redisDemoModel;
        }
        log.info("开始根据ID为{}查询数据库获取数据", id);
        DemoModel model = dataMap.get(id);
        // 缓存到redis
        redisTemplate.opsForValue().set("Demo::" + id, model);
        return model;
    }

    @Override
    public Boolean save(DemoModel model) {
        DemoModel model1 = new DemoModel(1L, "CCQ", 18);
        if (!dataMap.containsKey(model1.getId())) {
            dataMap.put(model1.getId(), model1);
        }
        DemoModel model2 = new DemoModel(2L, "wj", 15);
        if (!dataMap.containsKey(model2.getId())) {
            dataMap.put(model2.getId(), model2);
        }
        DemoModel model3 = new DemoModel(3L, "jqq", 19);
        if (!dataMap.containsKey(model3.getId())) {
            dataMap.put(model3.getId(), model3);
        }
        return true;
    }

    @Override
    @CachePut(key = "#id")
    public DemoModel updateById(Long id, String username) {
        log.info("开始根据ID为{}查询数据并且更新数据", id);
        DemoModel model = dataMap.get(id);
        model.setUsername(username);
        dataMap.put(model.getId(), model);
        // 更新redis
        // 缓存到redis
        redisTemplate.opsForValue().set("Demo::" + id, model);
        return model;
    }

    @Override
    @CacheEvict(key = "#id")
    public Boolean deleteById(Long id) {
        log.info("移除ID为{}的数据", id);
        dataMap.remove(id);
        redisTemplate.delete(String.valueOf(id));
        return true;
    }
}
